package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.exception.LyException;
import com.leyou.item.dto.CategoryDTO;
import com.leyou.item.entity.Category;
import com.leyou.item.entity.CategoryBrand;
import com.leyou.item.mapper.CategoryMapper;
import com.leyou.item.service.CategoryBrandService;
import com.leyou.item.service.CategoryService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper,Category> implements CategoryService {

    private CategoryBrandService categoryBrandService;

    public CategoryServiceImpl(CategoryBrandService categoryBrandService) {
        this.categoryBrandService = categoryBrandService;
    }

    @Override
    public CategoryDTO findCategoryById(Long id) {
        return new CategoryDTO(this.getById(id));
    }

    /***
     * 根据id查寻数据
     * @param ids
     * @return
     */
    @Override
    public List<CategoryDTO> listCategoryByIds(List<Long> ids) {

        //select * from tb_category where id in ();
        return CategoryDTO.convertEntityList(this.listByIds(ids));
    }



    /**
     * 根据父id查
     * @param pid
     * @return
     */
    @Override
    public List <CategoryDTO> listCategoryByParent(Long pid) {


        //selecgt * from tb_category where parent_id = #{pid};
        return CategoryDTO.convertEntityList(this.query().eq(pid!=null,"parent_id",pid).list());

    }


    /**
     * 根据品牌ID查询分类id
     * @param bid
     * @return
     */
    @Override
    public List <CategoryDTO> listCategoryByBrand(Long bid) {

        List <Long> categoryIds = this.categoryBrandService.query().eq("brand_id",bid).list().stream().map(CategoryBrand::getCategoryId).collect(Collectors.toList());

        //List <CategoryBrand> categoryBrands = this.categoryBrandService.query().select("category_id").eq("brand_id", bid).list();
        if(CollectionUtils.isEmpty(categoryIds)){
            throw new LyException(204,"该品牌没有分类");
        }
        return this.listCategoryByIds(categoryIds);
    }


}
